import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams, AlertController, ItemSliding, ToastController,Events} from 'ionic-angular';
import $ from "jquery";

import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {MessageListProvider} from '../../../providers/information/message-list/message-list.provider';
import {ToastService} from '../../../services/common/toast.service';
import {LoadingService} from "../../../services/common/loading.service";

@IonicPage()
@Component({
    selector: 'page-message-list',
    templateUrl: 'message-list.html',
    providers: [
        SideMenuService,
        MessageListProvider,
        ToastService
    ]
})
export class MessageListPage {
    // 视口高度
    get clientItemHeight():string{
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }
    // 确认弹框
    private alertObj: any;
    // 搜索关键字
    private keyword:string;
    // 消息类型
    private type:any;
    // 列表数据
    private messageData:any[]=[];
    // 预览列表长度
    private previewLength:number=0;
    // 是否是搜索消息
    private searchStatus:boolean;
    // 请求状态
    private requestStatus:boolean;
    // 消息列表标题
    private listType:string='消息';
    // 回车键请求状态
    private enterStatus:boolean=true;

    constructor(public navCtrl: NavController,
                public navParams: NavParams,
                public alertCtrl:AlertController,
                public toastCtrl:ToastController,
                private sideMenuService: SideMenuService,
                private tabsPage: TabsPage,
                private messageListProvider:MessageListProvider,
                private toastService:ToastService,
                private load: LoadingService,
                private event:Events
                ) {
    }
    //public backButtonHandle = () => this.backClickHandle();

    ionViewDidLoad() {
        this.navParams.get('keyword')?this.keyword=this.navParams.get('keyword'):'';
        this.navParams.get('type')?this.type=this.navParams.get('type'):null;
        this.navParams.get('title')?this.listType=this.navParams.get('title'):null;
        this.searchStatus=this.navParams.get('search');
        this.getMessageList(this.keyword,this.type,1,20,null,1);
    }

    ionViewDidEnter(){
        this.subscribeEvents();
    }


    subscribeEvents(){
        this.event.subscribe('message deteil',()=>{
            this.getMessageList(this.keyword,this.type,1,20,null,0);
        })
    }

    ionViewWillUnload(){
        this.event.unsubscribe('message deteil')
    }

    // 获取消息列表
    getMessageList(keyword,type,pageNum,pageSize,fn,loading){
        this.enterStatus=false;
        loading?this.load.showLoading():null;
        this.messageListProvider.getMessageList(keyword,type,pageNum,pageSize).subscribe((res)=>{
            if(res.total){
                this.getPrevMessage(res.list,this.type,loading);
                fn?fn():null;
            }else{
                this.getPrevMessage([],this.type,loading);
            }
        },error=>{
            this.enterStatus=true;
            fn?fn():null;
            this.requestStatus=true;
            loading?this.load.dismissLoading():null;
        })
    }

    // 获取预览消息
    getPrevMessage(list,type,loading){
        if(this.searchStatus){
            this.messageData=list;
            this.requestStatus=true;
            this.enterStatus=true;
            loading?this.load.dismissLoading():null;
            return false;
        }
        this.messageListProvider.getMsgOverview(type).subscribe((res)=>{
            this.enterStatus=true;
            loading?this.load.dismissLoading():null;
            this.requestStatus=true;
            if(res.length>0){
                this.previewLength=res.length;
                this.messageData=res.concat(list);
            }else{
                this.messageData=list;
            }
        },error=>{
            this.enterStatus=true;
            this.requestStatus=true;
            loading?this.load.dismissLoading():null;
        })
    }

    // 搜索
    searchHandle(){
        this.getMessageList(this.keyword,this.type,1,20,null,1);
    }

    // enter搜索
    inputKeyUp(e){
        if(('Enter' === e.key || 13 === e.keyCode)&&this.enterStatus){
            this.getMessageList(this.keyword,this.type,1,20,null,1);
        }
    }

    // 下拉刷新
    doRefresh(refresher){
        this.getMessageList(this.keyword,this.type,1,20,refresher.complete(),0);
    }

    // 返回
    backClickHandle() {
        this.navCtrl && this.navCtrl.pop(null, null);
    }

    // 到消息详情
    goToDetail(id,index) {
        let status=false;
        if(this.previewLength>0&&index<=(this.previewLength-1)){
            status=true;
        }
        this.navCtrl.push('MessageDetailPage',{
            id:id,
            status:status
        });
    }

    // 到收藏列表
    goToCollectionList () {
        this.navCtrl.push('CollectionListPage',{
            type:1
        });
    }

    // 删除消息
    deleteMessage(e,itemSliding:ItemSliding,id){
        e.stopPropagation();
        e.preventDefault();
        this.showConfirm(
            '确定删除?',
            ()=>{
                itemSliding.close();
                this.deleteRequest(id);
        },
            ()=>{
                itemSliding.close();
        })
    }

    // 删除消息请求
    deleteRequest(id){
        this.messageListProvider.deleteMessage(id).subscribe((res)=>{
            for(let m=0;m<this.messageData.length;m++){
                if(this.messageData[m].id==id){
                    this.messageData.splice(m,1)
                }
            }
        },error=>{
            if(error.status==500){this.toastService.showToast('删除失败')}
        })
    }

    /**
     * 确认框
     *
     * @private
     * @param {any} msg 询问的消息
     * @param {any} okCallback 用户点击确定后的回调
     * @param {any} cancelCallback 用户点击取消后的回调
     * @memberof ScheduleAddPage
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: '取消',
                handler: cancelCallback
            }, {
                text: '确定',
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }
}
